package com.hinnotek.amoeba.ui.activity.old

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.adapters.old.ImageSelectGridAdapter
import com.hinnotek.amoeba.base.BaseBean
import com.hinnotek.amoeba.bean.old.ProductTypePictures
import com.hinnotek.amoeba.databinding.ActivityProductManagermentModifyBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.utilities.ClickUtil
import com.lee.common.utils.SharedPreUtils
import com.hinnotek.amoeba.utilities.ToastUtils
import com.hinnotek.amoeba.utilities.Utils
import com.hinnotek.amoeba.viewmodels.ProductViewModel
import com.lee.common.network.net.ObserverState
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.xuexiang.xutil.common.StringUtils
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
import java.util.*


@AndroidEntryPoint
class ProductManagermentModifyActivity : BaseActivity<ActivityProductManagermentModifyBinding>(),
    View.OnClickListener,
    ImageSelectGridAdapter.OnAddPicClickListener {

    private var customDialog: CustomDialog? = null
    private var productTypeId = 0
    private var mAdapter: ImageSelectGridAdapter? = null
    private var mSelectList: MutableList<LocalMedia> = ArrayList<LocalMedia>()
    private lateinit var productTypePictures: MutableList<ProductTypePictures>

    private val viewModel by viewModels<ProductViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setLeftVisible(true)
        setTitle("产品结算价格")

        setContentView(R.layout.activity_product_managerment_modify)
    }

    override fun initVew() {
        bindingView.superButtonSubmit.setOnClickListener {
            if (ClickUtil.isFastClick()) {
                return@setOnClickListener
            }
            val productPrice = bindingView.etSettlementPrice.text.toString().trim()
            if (StringUtils.isEmpty(productPrice)) {
                ToastUtils.show(mContext, "请填写结算价格")
                return@setOnClickListener
            }
            customDialog = CustomDialog(mContext, "正在加载...")
            customDialog?.show()
            setProductManagament(productTypeId, productPrice)
        }
    }

    override fun setData() {
        productTypeId = intent.getIntExtra("productTypeId", 0)
        val title = intent.getStringExtra("title")
        val productTypeName = intent.getStringExtra("productTypeName")
        val productPrice = intent.getStringExtra("productPrice")
        productTypePictures =
            intent.getSerializableExtra("productTypePictures") as MutableList<ProductTypePictures>

        bindingView.tvChooseName.setText(title)
        bindingView.tvChooseType.setText(productTypeName)
        bindingView.etSettlementPrice.setText(productPrice)
        val manager = GridLayoutManager(mContext, 3, RecyclerView.VERTICAL, false)
        bindingView.rlvSettlementPrice.layoutManager = manager
        bindingView.rlvSettlementPrice.adapter =
            ImageSelectGridAdapter(mContext, this).also { mAdapter = it }
        for (data in productTypePictures) {
            val localMedia = LocalMedia()
            localMedia.setPath(data.pictureUrl)
            localMedia.setCompressPath(data.pictureUrl)
            mSelectList.add(localMedia)
        }
        mAdapter?.setSelectList(mSelectList)
        mAdapter?.setSelectMax(9)
        mAdapter?.setOnItemClickListener(object : ImageSelectGridAdapter.OnItemClickListener {
            override fun onItemClick(position: Int, v: View?) {
                PictureSelector.create(this@ProductManagermentModifyActivity)
                    .themeStyle(R.style.XUIPictureStyle).openExternalPreview(position, mSelectList)
            }
        })
    }

    /**
     * app端产品添加更新产品结算价格接口
     * @param productTypeId
     * @param productPrice
     */
    private fun setProductManagament(productTypeId: Int, productPrice: String) {

        viewModel.updateProductPrice(productTypeId,productPrice).observe(this,object : ObserverState<BaseBean>(){
            override fun onDataChange(data: BaseBean) {

                customDialog?.dismiss()
                setResult(Activity.RESULT_OK)

                val files1: MutableList<File> = ArrayList()
                for (i in mSelectList.indices) {
                    if (!mSelectList[i].path.startsWith("http")) {
                        files1.add(File(mSelectList[i].path))
                    }
                }
                val files = files1.toTypedArray()
                val idList: MutableList<Int> = ArrayList()

                for (i in productTypePictures.indices) {
                    val path: String = productTypePictures[i].pictureUrl
                    var id = -1
                    for (i1 in mSelectList.indices) {
                        if (path == mSelectList[i1].getPath()) {
                            id = i1
                        }
                    }
                    if (id == -1) {
                        idList.add(productTypePictures[i].productTypePictureId)
                    }
                }

                var deleteIds: String?
                val stringBuffer = StringBuffer()
                for (i in idList.indices) {
                    stringBuffer.append(idList[i].toString() + ",")
                }
                deleteIds = stringBuffer.toString()
                if (files.isEmpty() && StringUtils.isEmpty(deleteIds)) {
                    finish()
                    return
                }
                setProductManagament1(productTypeId, files, deleteIds)
                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                ToastUtils.showShort(mContext, msg)
                customDialog?.dismiss()
                super.onError(msg, code)
            }
        })

    }

    private fun setProductManagament1(productTypeId: Int, imgs: Array<File>, deleteIds: String) {
        val map = arrayOfNulls<RequestBody>(imgs.size)
        val createUser = SharedPreUtils.getString("userName")
        for (index in imgs.indices){
            val requestFile = imgs[index].asRequestBody("image/jpg".toMediaTypeOrNull())
            map[index] = requestFile
        }
        viewModel.addProductPicture(map,productTypeId,createUser,deleteIds).observe(this,object : ObserverState<BaseBean>(){
            override fun onDataChange(data: BaseBean) {
                ToastUtils.show(mContext, "成功")
                finish()
                super.onDataChange(data)
            }
            override fun onError(msg: String?, code: Int) {
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }
        })
       /* requestParams = RequestParams()
        requestParams.put("productTypeId", productTypeId)

        val userName: String = sharedPreferences.getString("userName", "")
        requestParams.put("createUser", userName)
        requestParams.put("deleteIds", deleteIds)
        //        if (!StringUtils.isEmpty(deleteIds)){
//            requestParams.put("deleteIds",deleteIds);
//        }
        try {
            requestParams.put("imgs", imgs)
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }*/
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    // 图片选择
                    mSelectList = PictureSelector.obtainMultipleResult(data)
                    mAdapter?.setSelectList(mSelectList)
                    mAdapter?.notifyDataSetChanged()
                }
            }
        }
    }


    override fun onClick(v: View) {}
    override fun onAddPicClick() {
        Utils.getPictureSelector(this)
            .selectionMedia(mSelectList)
            .maxSelectNum(9)
            .forResult(PictureConfig.CHOOSE_REQUEST)
    }
}